package com.handpay.zztong.hp.onlineshop.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.MD5;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.merchantinfo.MerchantInfo;
import com.handpay.zztong.hp.main.model.merchantinfo.MerchantInfoModel;
import com.handpay.zztong.hp.onlineshop.model.showloan.RecordUserVisitModel;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.utils.AccountUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Hashtable;


/**
 * 微服务-代还信用卡
 */
public class ShowLoanHtmlActivity extends ZZTongActivity implements OnClickListener {
    /**
     * 加载网页的webview
     */
    public WebView webView;
    /**
     * 网页加载的地址
     */


    private MyWebViewClient webViewClient;
    private ProgressBar progressBar;
    private ImageView btnfunction;
    private String indexurl;
    public static final String ShowHtml_Html_Path_Key = "ShowHtml_Html_Path_Key";

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.tv_loan_title), true);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_show_html);
        super.onCreate(savedInstanceState);
        webView = (WebView) findViewById(R.id.userServiceWebView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        //dialog_market_exit_btn

        btnfunction = (ImageView) findViewById(R.id.btn_goToFunction);
        btnfunction.setImageBitmap(null);
        btnfunction.setBackgroundResource(R.drawable.dialog_market_exit_btn);
        btnfunction.setOnClickListener(this);
        //获取商户信息并且加载网页
        getMerchantInfo();
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webViewClient = new MyWebViewClient();
        webView.setWebViewClient(webViewClient);
//        webView.clearCache(true);
//        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        indexurl = getIntent().getStringExtra(ShowHtml_Html_Path_Key);

    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (TextUtils.isEmpty(AccountUtils.getUserName(ShowLoanHtmlActivity.this)) || TextUtils.isEmpty(AccountUtils.getAccountPhone(ShowLoanHtmlActivity.this))
                    || TextUtils.isEmpty(AccountUtils.getUsercertNo(ShowLoanHtmlActivity.this)) || TextUtils.isEmpty(AccountUtils.getUserCardNo(ShowLoanHtmlActivity.this))) {
                showError();
            } else {
                String temp_value = formatData4json();
                webView.loadUrl("javascript:if (typeof getUserModelCallback != 'undefined' && getUserModelCallback instanceof Function) {	getUserModelCallback('" + temp_value + "');}");
                if (progressBar != null)
                    progressBar.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    private String formatData4json() {
        String temp_name = AccountUtils.getUserName(this);
        String temp_phone = AccountUtils.getAccountPhone(this);
        String temp_certNo = AccountUtils.getUsercertNo(this);
        String temp_cardNo = AccountUtils.getUserCardNo(this);
        String date = CommonUtils.getTimestamp(new Date(), "yyyyMMdd");
        String key = temp_certNo + date + "HaN_yIn_ke_JI";
//        Log.i(HPLog.TAG_RESULT,temp_name+"|"+temp_phone+"|"+temp_certNo+"|"+temp_cardNo+"|"+date+"|"+key);
        String encrypt = new MD5().getMD5ofStr(key);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", temp_name);
            jsonObject.put("phone", temp_phone);
            jsonObject.put("certNo", temp_certNo);
            jsonObject.put("cardNo", temp_cardNo);
            jsonObject.put("encrypt", encrypt.toLowerCase());
            return jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_goToFunction) {
            goBack();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    private void showError() {
        showAlertDialog(this, getString(R.string.tip), "数据加载异常，请重新尝试！", false, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goBack();
                dialog.dismiss();
            }
        });
    }

    private void getRecordUserVisit() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put("merchantCode", SecureManager.getInstance().des(AccountUtils.getMerchantCode(this), 1, null));
        params.put("businessType", "01");
        params.put("userInfo", SecureManager.getInstance().des(AccountUtils.getAccountPhone(this) + "|" + AccountUtils.getUserCardNo(this), 1, null));
        new RecordUserVisitModel().doRecordUserVisitPost(this, params, null);
    }


    private void getMerchantInfo() {
        //触发条件：1 必须审核通过，2 内存中不存在姓名身份证等信息
//        if (TextUtils.isEmpty(AccountUtils.getUserName()) && TextUtils.isEmpty(AccountUtils.getUsercertNo()) && TextUtils.isEmpty(AccountUtils.getUserCardNo())) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, ZZTongActivity.newBankFlag);

        new MerchantInfoModel().doMerchantInfoPost(this, params, new BusinessEngineListener<MerchantInfo>() {
            @Override
            public void callbackBusinessResponse(MerchantInfo bean) {

                String phone = bean.getPhone();
                phone = SecureManager.getInstance().des(phone, 0, null);
                String name = bean.getName();
                name = SecureManager.getInstance().des(name, 0, null);
                String certNo = bean.getCertNo();
                certNo = SecureManager.getInstance().des(certNo, 0, null);
                String cardNum = bean.getCardNum();
                cardNum = SecureManager.getInstance().des(cardNum, 0, null);
                AccountUtils.setAccountPhone(ShowLoanHtmlActivity.this, phone);
                AccountUtils.saveUserName(ShowLoanHtmlActivity.this, name);
                AccountUtils.saveUsercertNo(ShowLoanHtmlActivity.this, certNo);
                AccountUtils.saveUserCardNo(ShowLoanHtmlActivity.this, cardNum);
                webView.loadUrl(indexurl);
                getRecordUserVisit();
            }
        });

//        doJsonPost(this, ZZTongActivity.DO_zztGetMerchantInfo, MerchantInfo.class, params);
//        } else {
//            webView.loadUrl(indexurl);
//            getRecordUserVisit();
//        }
    }
}
